package com.jprocms.module.cms.es.convert;

import com.jprocms.module.cms.es.dto.ContentEsDto;
import com.jprocms.module.cms.es.dto.ContentTxtDto;
import com.jprocms.module.cms.es.po.EsContent;
import org.apache.commons.collections4.CollectionUtils;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;
import org.mapstruct.factory.Mappers;

import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jprocms
 */
@Mapper
public interface EsContentConverter {

    EsContentConverter INSTANCE = Mappers.getMapper(EsContentConverter.class);

    @Mapping(target = "txts", expression = "java( convert2Txt( source.getTxts()))")
    @Mapping(target = "docs", expression = "java( convert2Txt( source.getDocs()))")
    @Mapping(source = "releaseTime", target = "releaseTime", qualifiedByName = "customTimeToOffsetTimeMapping")
    EsContent convert(ContentEsDto source);

    default List<ContentTxtDto> convert2Txt(List<String> txts) {
        if (CollectionUtils.isEmpty(txts)) {
            return null;
        }
        return txts.stream().map(t -> new ContentTxtDto(t)).collect(Collectors.toList());
    }

    @Named("customTimeMapping")
    default OffsetDateTime customTimeMapping(Date dateTime) {
        return dateTime != null ? OffsetDateTime.ofInstant(dateTime.toInstant(), ZoneOffset.UTC) : null;
    }

    @Named("customTimeToOffsetTimeMapping")
    default Date customTimeToOffsetTimeMapping(OffsetDateTime dateTime) {
        return dateTime != null ? Date.from(dateTime.toInstant()) : null;
    }

}
